//
//  PopElemntView.m
//  EpointFrame5
//
//  Created by Pill Gong on 14-4-16.
//  Copyright (c) 2014年 Epoint. All rights reserved.
//

#import "PopElementView.h"
#import "UIView+Addtions.h"

@interface PopElementView () <PopElementItemDelegate>

@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) NSMutableArray *itemArray;

@property (nonatomic, assign) PopElementItem *selectedItem;

@end

@implementation PopElementView {
    UIColor *normalColor;
    UIColor *highlightColor;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.contentView = [[UIScrollView alloc] initWithFrame:self.bounds];
        [self addSubview:_contentView];
        
        [self setDefaultValues];
    }
    return self;
}

- (void)setDefaultValues {
    normalColor = [UIColor whiteColor];
    highlightColor = COLOR(249, 247, 84);
}

- (void)setTitles:(NSArray *)titles {
    _titles = titles;
    
    if (self.itemArray == nil) {
        self.itemArray = [[NSMutableArray alloc] initWithCapacity:_titles.count];
    }
    [self removeAllSubViews];

    CGFloat startY = 0;
    int count = 0;
    for (NSString *title in titles) {
        count++;
        PopElementItem *item = [[PopElementItem alloc] initWithFrame:CGRectMake(0, startY, self.width, PopElementItemHeight-1)];
        item.title = title;
        item.delegate = self;
        [_itemArray addObject:item];
        [_contentView addSubview:item];
        
        if (count < titles.count) {
            [self addLines:item.bottom];
        }
        startY += (PopElementItemHeight+1);
    }
}

- (void)addLines:(CGFloat)bottom {
    //27
    UIImageView *line1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, bottom, self.width, 1)];
    line1.backgroundColor = COLOR(27, 27, 27);
//    line1.alpha = 0.8;
    [_contentView addSubview:line1];
    //51
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, bottom+1, self.width, 1)];
    line2.backgroundColor = COLOR(51, 51, 51);
//    line2.alpha = 0.8;
    [_contentView addSubview:line2];
}

- (void)removeAllSubViews {
    
    [_itemArray removeAllObjects];
    for (UIView *subView in _contentView.subviews) {
        [subView removeFromSuperview];
    }
}

- (void)selectItemAtIndex:(int)index {
    if (index >= _itemArray.count) {
        return;
    }

    _selectedIndex = index;
    PopElementItem *item = [_itemArray objectAtIndex:_selectedIndex];
    if (_selectedItem) {
        _selectedItem.isSelected = NO;
    }
    _selectedItem = item;
    item.isSelected = YES;
}

#pragma mark - PopElementItemDelegate

- (void)popElementItemDidSelected:(PopElementItem *)elementItem {
    int index = [_itemArray indexOfObject:elementItem];
    [self selectItemAtIndex:index];
    if (_delegate && [_delegate respondsToSelector:@selector(popElementViewDidSelectedAtIndex:)]) {
        [_delegate popElementViewDidSelectedAtIndex:index];
    }
}

@end
